<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>10_ComponentLife</title>
</head>
<body>
<div id="example"></div>

<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel">
    /*
    需求: 自定义组件
      1. 让指定的文本做显示/隐藏的动画
      2. 切换时间为2S
      3. 点击按钮从界面中移除组件界面
     */
    class MyComponent extends React.Component {
        constructor(props) {
            super(props);

            this.state = {
                opacity: 1
            }

            this.removeComponent = this.removeComponent.bind(this);
        }

        removeComponent() {
            ReactDOM.unmountComponentAtNode(document.getElementById("example"));
        }

        // 声明周期函数
        componentDidMount() {
            // 设置定时器
            console.log("componentDidMount....");

            this.number = setInterval(() => {
                let {opacity} = this.state;
                opacity -= 0.1;

                if (opacity <= 0) {
                    opacity = 1;
                }
                console.log("定时器");
                this.setState({opacity})
            }, 200);
        }

        // 声明周期函数
        componentWillUnmount() {
            // 移除定时器
            clearInterval(this.number);
        }
        render() {
            const {opacity} = this.state;
            return (
                <div>
                    <h2 style={{opacity}}>React 好简单！</h2>
                    <button onClick={this.removeComponent}>不活了</button>
                </div>
            );
        }
    }

    ReactDOM.render(<MyComponent/>, document.getElementById("example"));
</script>